package com.example.helloandroid;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.TelephonyManager;
import android.util.Log;

public class IncomingCallReceiver extends BroadcastReceiver  
{
	private static com.example.helloandroid.SpeakName speakname;
	@Override
	public void onReceive (Context ctx, Intent intent)
	{
		Bundle bundle = intent.getExtras();

		if ( null == bundle)
			return;
		String state = bundle.getString(TelephonyManager.EXTRA_STATE);
		WriteText ( "State: " + state );
		if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
		{
			String m_NameToSpeak = null;			
			ContentResolver cr = ctx.getContentResolver();	
			String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
			WriteText ( "Incoming Number: " + phonenumber);
			try
			{
				m_NameToSpeak = getNameFromNumber(phonenumber, cr);
			}
			catch (Exception ex)
			{
				WriteText( ex.toString());
			}
			if ( null != m_NameToSpeak )
			{
				// Start the thread to speak
				speakname = new SpeakName(m_NameToSpeak);
				speakname.start();
			}
		}
		else 
		{
			// Stop the speaking thread
			WriteText("Call Done. Stop Speaking");
			speakname.StopSpeaking();
			try 
			{
				speakname.stop();
			}
			catch ( Exception ex)
			{
				WriteText ( ex.toString());
			}
		}
	}

	private String getNameFromNumber ( String PhoneNumber, ContentResolver cr )
	{
		Uri NameLookUpUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(PhoneNumber));
		if ( null == NameLookUpUri )
			return null;
		
		Cursor c = null;
		String dispName = null;
		try
		{
			// query time
			c = cr.query(NameLookUpUri, new String[]{Contacts.DISPLAY_NAME},null,null,null);
			c.moveToFirst();
			dispName = c.getString(0);
			
		}
		catch ( Exception ex )
		{
			Log.e("HelloAndroid" , ex.toString());
		}
		finally
		{
			c.close();
		}
		return dispName;
	}
	
	private void WriteText ( String msg )
	{
		Log.i("IncomingCallReceiver",  msg );
	}	
}
